from django.db.models import Avg, Count, Max, Min, Sum, F, Q
from django.http import HttpResponse
from django.shortcuts import render

from .models import Book, Author
from .forms import MessageBoardFrom, RegisterForm

#请求验证装饰器
from django.views.decorators.http import require_http_methods

# Create your views here.

def avg_view(request):
    result = Book.objects.aggregate(Avg('price'))
    print(result)
    return HttpResponse("result")

def count_view(request):
    result = Book.objects.aggregate(book_num = Count('id'))
    print(result)
    return HttpResponse("result")

def max_min_view(request):
    result = Author.objects.aggregate(Max('age'),Min('age'))
    print(result)
    return HttpResponse("result")

def sum_view(request):
    result = Book.objects.annotate(total = Sum('bookorder__price')).values('name','total')
    print(result.query)
    return HttpResponse("result")


def f_view(request):
    Book.objects.update(price=F('price')-10)


def q_view(request):
    result = Book.objects.filter(Q(price__gte=20) | Q(price__lte=10))
    print(result.query)
    return HttpResponse("result")

@require_http_methods(["GET", "POST"])
def index(request):
    if request.method == "GET":
        form = MessageBoardFrom()
        return render(request, "index.html",context={"form":form})
    else:
        #对post请求提交上来的数据，用表单验证s是否满足要求
        form = MessageBoardFrom(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            email = form.cleaned_data['email']
            return HttpResponse(f"{title} {content} {email}")
        else:
            print(form.errors)

@require_http_methods(["GET", "POST"])
def register_view(request):
    if request.method == "GET":
        return render(request,"register.html")
    else:
        form = RegisterForm(request.POST)
        if form.is_valid():
            telephone = form.cleaned_data['telephone']
            return HttpResponse(f"telephone:{telephone}")
        else:
            print(form.errors)
            return HttpResponse("error")
